<template>
    <div class="check_order">
        <div class="post-address-container stripe-border--bottom" @click="$router.push('/delivery_address')" v-if="requestDone&&address.name">
            <div class="post-info">
                <div class="post-name-phone">
                    <div class="post-name">姓名：{{address.name}}（{{address.phone}}）</div>
                </div>
                <div class="post-address">
                    地址：{{address.province+address.city+address.district+address.address}}
                </div>
            </div>
            <div class="allow-right">
                <i class="mint-cell-allow-right"></i>
            </div>
        </div>
        <div class="post-address-container stripe-border--bottom" v-if="requestDone&&!address.name" @click="$router.push('/delivery_address')">
            
            <div class="post-info-add">
                <div class="post-name-phone">
                    <span class="icon-add"></span>
                </div>
                <div class="post-address" style="flex: 1;">
                    新建收货地址
                </div>
            </div>
            <div class="allow-right">
                <i class="mint-cell-allow-right"></i>
            </div>
        </div>
        <div class="product_items_container">
            <productListItem v-for="(productItem, index) in products" :key="index" :productItem="productItem" :show-border="index != products.length-1"> 
            </productListItem>
        </div>
        <div class="remark">
            <mt-field label="买家留言" placeholder="请填写留言" v-model="remark"></mt-field>
        </div>
        <div class="action_btns">
            <div class="summary">
                <span>合计</span><span class="summary_price">{{getProductsPrice().price?"¥"+getProductsPrice().price:"¥0"}}</span>
            </div>
            <div class="go_to_check" @click="addOrder">
                去支付({{getProductsPrice().count}})
            </div>
        </div>
    </div>
</template>
<script>
import utils from '@utils'
import { addOrder, payOrder, cartBuy, productDetailBuyNow } from './../api'
import { Field } from 'mint-ui'

export default {
    name: 'app',
    components: {
        mtField: Field
    },
    mixins: [ utils.MixinBase ],
    data() {
        return {
            name: 'test',
            address: {},
            isCart: false,
            products: [],
            requestDone: false,
            orderId: '',
            shoppingCartIds: [],
            remark: ''
        }
    },
    mounted() {
        this.$indicator.open('加载中...');
        this.wechatInit().then(()=> {
            this.wechatConfigInit().then(() => {
                this.init();
            },()=> {
                this.init();
            })
        }, ()=> {
            this.init();
        });
    },
    destoryed() {
        sessionStorage.removeItem('deliveryAddressItem')
    },
    methods: {
        init() {
            //productItemId 商品详情立即购买
            //cartIds 购物车立即购买
            var qs = utils.getQueryObject();
            if(qs.productId && qs.number) {
                let params = {
                    productId: qs.productId,
                    productItemId: qs.productItemId,
                    number: qs.number,
                };

                if(qs.addons) {
                    params.addons = JSON.parse(decodeURIComponent(qs.addons))
                }
                if(qs.attributes) {
                    params.attributes = JSON.parse(decodeURIComponent(qs.attributes))
                }

                productDetailBuyNow(params).then((data) => {
                    if(sessionStorage.getItem('deliveryAddressItem')) {
                        this.address = JSON.parse(sessionStorage.getItem('deliveryAddressItem'))
                    } else {
                        this.address = data.address||{};
                    }
                    this.isCart = data.isCart;
                    this.products = data.products;
                    this.$indicator.close();
                    this.requestDone = true;
                })
            } else {
                cartBuy({
                    ids: qs.cartIds.split(",")//购物车明细ID
                }).then(data => {
                    if(sessionStorage.getItem('deliveryAddressItem')) {
                        this.address = JSON.parse(sessionStorage.getItem('deliveryAddressItem'))
                    } else {
                        this.address = data.address||{};
                    }
                    this.isCart = data.isCart;
                    this.products = data.products;
                    this.shoppingCartIds = data.shoppingCartIds;
                    this.$indicator.close();
                    this.requestDone = true;

                    
                })
            }
        },
        getProductsPrice() {
            var price = 0, count = 0;
            this.products.map(item => {
                price += item.dpPrice * item.number;
                count += item.number;
            });
            return {price: price.toFixed(2), count: count};
        },
        addOrder() {
            if(this.$parent.$data.orderId) {
                this.payOrder(this.$parent.$data.orderId);
            } else {
                if(!this.address.id) {
                    this.$toast("请选择收获地址");
                    return;
                }
                var postage = 0;
                var params = {
                    addressId: this.address.id,
                    postage: postage,
                    isFromCart: this.isCart,
                    transactionPrice: Number(this.getProductsPrice().price) + Number(postage),
                    shoppingCartIds: this.shoppingCartIds,
                    remark: this.remark || '',
                    orders: this.products.map(item => {
                        return {
                            productId: item.productId,
                            productItemId: item.productItemId,
                            number: item.number,
                            price: item.dpPrice,
                            addons: (item.addons||[]).map(item => {
                                return {
                                    addonId: item.addonId,
                                    addonItemId: item.addonItemId
                                }
                            }),
                            attributes: (item.attributes||[]).map(item => {
                                return {
                                    attributeId: item.attributeId,
                                    attributeItemId: item.attributeItemId
                                }
                            })
                        }
                    })
                }

                this.$indicator.open({
                    spinnerType: 'fading-circle',
                    text: '开始下单'
                });
                
                addOrder(params).then((data) => {
                    this.$parent.$data.orderId = data;
                    this.$indicator.close();
                    this.payOrder(data);
                }).catch(err => {
                    this.$indicator.close();
                    this.$toast(err&&err.info)
                });
            }
        },
        payOrder(orderId){
            payOrder({id: orderId}).then((js_json) => {
                this.$indicator.open({
                    spinnerType: 'fading-circle',
                    text: '开始支付'
                });
                wx.chooseWXPay({
                    timestamp: js_json['timeStamp'], // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: js_json['nonceStr'], // 支付签名随机串，不长于 32 位
                    package: js_json['package'], // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                    signType: js_json['signType'], // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: js_json['paySign'], // 支付签名
                    success: (res) => {
                        this.$indicator.close();
                        this.$indicator.open({
                            spinnerType: 'fading-circle',
                            text: '支付成功'
                        });
                        setTimeout(()=> {
                            utils.goToPage("my_order.html?");
                        }, 1000);
                    },
                    fail: (failReason) => {
                        alert(JSON.stringify(failReason));
                        this.$indicator.close();
                    },
                    cancel: () => {
                        this.$indicator.close();
                        this.$toast("你取消了支付");
                    }
                })
            },(js_json) => {
                alert(JSON.stringify(js_json));
            });
        }
    }
}
</script>
<style>
    .check_order {
        padding-bottom: 50px;
        background: #f7f7f7;
    }
    .check_order .mint-cell-wrapper{
        background-image: none;
    }
    .check_order .mint-cell:last-child {
        background-image: none;
    }
    .check_order .mint-field .mint-cell-title {
        width: 64px;
    }
    .check_order .mint-cell {
        min-height: 1.2rem;
    }
    .post-address-container {
        background: #fff;
        padding: 14px 0 14px 12px;
        display: flex;
        position: relative;
        margin: 10px;
        border-radius: 8px;
        overflow: hidden;
    }

    .allow-right {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 24px;
    }
    .allow-right .mint-cell-allow-right::after {
        right: 12px;
    }
    .post-info {
        flex: 1;
        padding-right: 30px;
    }
    .post-info-add {
        display: flex;
    }
    .post-name-phone {
        display: flex;
        color: #333;
    }
    .post-name-phone .icon-add {
        width: 30px;
        height: 30px;
        background: #446fff;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 4px;
        color: #fff;
        margin-right: 10px;
        font-size: 18px;
    }
    .post-name {
        flex: 1;
    }
    .post-phone {
        width: 4rem;
        text-align: right;
    }
    .post-address {
        color: #666;
        display: flex;
        align-items: center;
    }
    .product_items_container {
        margin: 10px;
        border-radius: 8px;
        overflow: hidden;
    }

    .stripe-border--bottom:after {
        bottom: 0;
    }

    .stripe-border--bottom:after, .stripe-border--top:before {
        left: 0;
        right: 0;
        content: "";
        height: 2px;
        position: absolute;
        background: -webkit-repeating-linear-gradient(135deg,#ff6d6d,#ff6d6d 20%,transparent 0,transparent 25%,#3283fa 0,#3283fa 45%,transparent 0,transparent 50%);
        background: repeating-linear-gradient(-45deg,#ff6d6d,#ff6d6d 20%,transparent 0,transparent 25%,#3283fa 0,#3283fa 45%,transparent 0,transparent 50%);
        background-size: 80px;
    }

    .action_btns {
        display: flex;
        position: fixed;
        bottom: 0;
        height: 44px;
        width: 10rem;
        box-shadow: 0 -1px 1px rgba(0,0,0,.1);
        background: #fff;
        justify-content: space-between;;
        align-items: center;
    }
    .summary {
        flex: 1;
        align-items: center;
        display: flex;
        padding-right: 16px;
        margin-left: 10px;
    }
    .summary_price {
        color: #fe0000;
    }
    .go_to_check {
        width: 3rem;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        background: -webkit-linear-gradient(right, red, blue);
        background: linear-gradient(to left, #ff2525, #ff700a);
        margin-right: 10px;
        height: 32px;
        border-radius: 18px;
    }
    .remark {
        border-radius: 8px;
        overflow: hidden;
        margin: 10px;
        background: #fff;
    }
</style>